package demo.isometric.utils {
	import as3isolib.core.IsoDisplayObject;
	import as3isolib.display.IsoSprite;
	import as3isolib.display.IsoView;
	import as3isolib.geom.IsoMath;
	import as3isolib.geom.Pt;
	
	import com.sshc625.log.Logger;
	
	import demo.gemo.GridPoint;
	import demo.isolib.Tile;
	import demo.isolib.World;
	
	import flash.display.Bitmap;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;

	/**
	 */
	public class DragManager {

		private static var _instance:DragManager;

		private var _proxy:Sprite;
		private var _view:IsoView;
		private var _obj:IsoDisplayObject;

		public function DragManager(enf:SingletonEnforcer) {

		}

		public static function getInstance():DragManager {
			if (_instance == null)
				_instance = new DragManager(new SingletonEnforcer());
			return _instance;
		}

		/**
		 * @usage
		 * var obj3:IsoBox = new IsoBox();
		 * obj3.addEventListener(MouseEvent.MOUSE_DOWN, onIsoObjMouseDown);
		 *
		 * private function onIsoObjMouseDown(e:ProxyEvent):void {
		 * 		DragManager.getInstance().drag(IsoDisplayObject(e.target), view);
		 * }
		 *
		 * @parameter obj	the IsoDisplayObject which can be drag
		 * @parameter view
		 */
		public function drag(obj:IsoDisplayObject, view:IsoView):void {
			if( (obj==null) || (view==null) ) {
				throw new Error("IllegalArgumentsException");
			}
			_view = view;
			_obj = obj;
			
			var bmp:Bitmap = new Bitmap(_obj.getRenderData().bitmapData)
			bmp.x = -_obj.length;
			bmp.y = -_obj.height;
			
			_proxy = new Sprite();
			_proxy.alpha = 0.5;
			_proxy.addChild(bmp);
			//_proxy.x = -_obj.length/2;
			//_proxy.y = -_obj.height/2;
			_proxy.addEventListener(Event.ENTER_FRAME, onProxyEnterFrame);			
			_view.addChild(_proxy);
			
			_view.stage.addEventListener(MouseEvent.MOUSE_UP, drop);
		}

		private function onProxyEnterFrame(e:Event):void {
			if (_proxy != null) {
				_proxy.x = _view.mouseX;
				_proxy.y = _view.mouseY;
			}

		}

		private function drop(e:Event = null):void {
			var p:Point = new Point(_proxy.x, _proxy.y);
			var p2:Pt = _view.localToIso(p);
			
			var gridPt:GridPoint = (this._view as World).isoToGridAndRound(p2);			
			_obj.moveTo(gridPt.gridX, gridPt.gridY, 0);
			
			(_obj as Tile).selected = false;
			
			//clean up
			_view.removeChild(_proxy);
			_view.stage.removeEventListener(MouseEvent.MOUSE_UP, drop);
			_proxy.removeEventListener(Event.ENTER_FRAME, onProxyEnterFrame);
			_proxy = null
		}

		public function get obj():IsoDisplayObject {
			return _obj;
		}
	}
}

class SingletonEnforcer {
}
